package com.tian.job;

import com.tian.entity.TradeVerifyFileContent;
import com.tian.service.TradeVerifyFileContentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年08月29日 21:34
 * 在线刷题 1200+题和1000+篇干货文章：<a href="https://woaijava.cc/">博客地址</a>
 * <p>
 * 拉取对账文件，并解析内容，入库
 *
 * FTP下载文件到本地  参考例子：https://blog.csdn.net/qq_39425322/article/details/127885341
 */
@Slf4j
@Component
public class ReadVerifyFileTask {
    /**
     * 文件目录 Date
     */
//    private final static String FILE_PATH_NAME = "D:\\verify\\xxx" + "\\20230830";
    private final static String FILE_PATH_NAME = "D:\\verify";
    /**
     * 每次批量入库记录数
     */
    private final static int PAGE_SIZE = 50;

    @Resource
    private TradeVerifyFileContentService deroctTradeVerifyFileContentService;

    /**
     * 每20秒执行一次  每天凌晨2点开始对账文件解析
     */
    @Scheduled(cron = "0/20 * * * * ? ")
    public void process() {
        log.info("读取目录下的文件-------开始");
        File folder = new File(FILE_PATH_NAME);
        File[] files = folder.listFiles();

        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {

                    log.info("文件名称:{}", file.getPath());

                    List<TradeVerifyFileContent> verifyFileDtoList = new ArrayList<>();

                    BufferedReader reader = null;
                    try {
                        reader = new BufferedReader(new FileReader(file.getPath()));
                        //逐行读取
                        String line = reader.readLine();

                        int i = 0;
                        boolean isExist = false;

                        while (line != null) {
                            //按照逗号,分割每一行内容
                            String[] fields = line.split(",");
                            //5个字段使用分隔符逗号,
                            //202308080808100003,333.33,2023-08-29 03:23:12,1,2023-09-29
                            if (fields.length == 5) {

                                TradeVerifyFileContent tradeVerifyFileContent = new TradeVerifyFileContent();
                                String orderNo = fields[0];

                                //避免重复处理的文件，当文件的第一行已经入库了，那就表示整个文件内容都入库了
                                if (i == 0) {
                                    TradeVerifyFileContent verifyFileContent = deroctTradeVerifyFileContentService.selectByOrderNo(orderNo);
                                    if (verifyFileContent != null) {
                                        log.info("已入库");
                                        isExist = true;
                                    }
                                }

                                tradeVerifyFileContent.setOrderNo(orderNo);
                                tradeVerifyFileContent.setMoney(new BigDecimal(fields[1]));

                                try {
                                    //订单创建时间
                                    DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    Date date = fmt.parse(fields[2]);
                                    tradeVerifyFileContent.setCreateTime(date);
                                } catch (ParseException e) {
                                    log.error("订单创建日期格式转换异常", e);
                                    throw new RuntimeException(e);
                                }
                                tradeVerifyFileContent.setStatus(Integer.parseInt(fields[3]));
                                try {
                                    DateFormat fmt1 = new SimpleDateFormat("yyyy-MM-dd");
                                    Date date1 = fmt1.parse(fields[4]);
                                    //还款日期格式转换
                                    tradeVerifyFileContent.setLoanDate(date1);
                                } catch (ParseException e) {
                                    log.error("还款日志格式转换异常", e);
                                    throw new RuntimeException(e);
                                }
                                tradeVerifyFileContent.setSendStatus(0);
                                verifyFileDtoList.add(tradeVerifyFileContent);
                            }
                            i++;
                            // 继续读取下一行
                            line = reader.readLine();
                            //读下一个文件  52---50
                            if (!isExist && i != 0 && i % PAGE_SIZE == 0) {
                                //批量 保存到数据库中
                                deroctTradeVerifyFileContentService.batchInsert(verifyFileDtoList);
                                verifyFileDtoList = new ArrayList<>();
                            }
                            //处理 分页 多余的数据
                            if (line == null && i % PAGE_SIZE != 0) {
                                deroctTradeVerifyFileContentService.batchInsert(verifyFileDtoList);
                            }
                        }

                    } catch (Exception e) {
                        log.error("文件解析异常", e);
                    } finally {
                        try {
                            if (reader != null) {
                                reader.close();
                            }
                        } catch (IOException e) {
                            log.error("数据流关闭异常", e);
                        }
                    }
                }
            }
        }
        log.info("读取目录下的文件-------结束");
    }
}
